package com.ai.module.chat.config.interceptor;

import com.ai.module.chat.common.base.ThreadLocalContext;
import com.ai.module.chat.common.constant.RedisKeyStringConstant;
import com.ai.module.chat.common.constant.StringConstant;
import com.ai.module.chat.config.advice.exception.BusinessException;
import com.ai.module.user.domain.vo.UserLoginInfo;
import com.ai.module.chat.util.RedisTemplateUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: MrHe
 * @create: 2024-01-27 01:17
 * @description:
 **/

//@Component
public class CorsFilter implements Filter {

    private static final String [] FILTER_LIST = {"webSocket"};
    

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain chain) throws IOException, ServletException {

        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String servletPath = httpServletRequest.getServletPath();

        // anyMatch： 有一个条件满足就返回true
        boolean match =false;
                // Arrays.stream(FILTER_LIST).anyMatch(servletPath::contains);
        // boolean match = Arrays.stream(FILTER_LIST).anyMatch(filterUrl -> servletPath.startsWith(filterUrl));

        // 符合ws请求的url开始校验，其他请求一概放过
        if (match) {
            String headToken = httpServletRequest.getHeader(StringConstant.TOKEN);
            System.out.println("token = " + headToken);

            HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

            if (StringUtils.isNotBlank(headToken)) {
                // 校验
                if (StringUtils.isBlank(headToken)){
                    httpServletResponse.setStatus(401);
                    throw new BusinessException( 401,"请重新登录");
                }
                String userTokenKey = String.format(RedisKeyStringConstant.USER_INFO, headToken);

                UserLoginInfo userLoginInfo =  RedisTemplateUtils.get(userTokenKey);
                if (userLoginInfo ==null){
                    httpServletResponse.setStatus(401);
                    throw new BusinessException("登录已过期,请重新登录",401);
                }
                ThreadLocalContext.set(StringConstant.USER_INFO,userLoginInfo);
                ThreadLocalContext.set(StringConstant.TOKEN, headToken);
                ThreadLocalContext.set(StringConstant.CURRENT_TIME,System.currentTimeMillis());
                ThreadLocalContext.setUserLoginInfo(userLoginInfo);
                chain.doFilter(servletRequest, servletResponse);
            }else {
                httpServletResponse.setStatus(401);
                throw new BusinessException("请求头缺少loginToken");
            }
//            else {
//                JSONObject result = new JSONObject();
//                HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
//                httpServletResponse.setContentType("application/json;charset=utf-8");
//                httpServletResponse.setCharacterEncoding("utf-8");
//                PrintWriter writer = httpServletResponse.getWriter();
//                writer.write(result.toJSONString());
//                writer.flush();
//                writer.close();
//            }
        } else {
            // 不包含过滤清单，直接放过请求
            chain.doFilter(servletRequest, servletResponse);
        }
 
    }
    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

}
